import allure
import pytest
import requests
from api_keyword.api_key import ApiKey
from params.allParams import URL, URL2

# 逻辑层

# 发单员正常发起帮助
class ApiCase03:
    """登录"""
    def test_login(self):
        allure.dynamic.title("登录")
        apiKey = ApiKey()
        userInfo = {
            "js_code": "0e3AaY100QWUWT1X7u000XkK1k4AaY17"
        }
        url = f"{URL}/api/wx/user/login"
        response = apiKey.post(
            url=url,
            json=userInfo,
            headers={"Content-Type": "application/json"}
        )
        with allure.step(f"发送登录请求"):
            print(f'登录接口请求响应信息:{response.text}')
            print(f'响应状态码:{response.status_code}')
            print(f'响应头:{response.headers}')
            msg = apiKey.get_text(response.text, 'msg')
            print(f"响应消息：{msg}")
            assert msg == '登录成功'

    """获取服务列表  /api/server/get/uid"""
    def test_serverList(self, token_fix):
        allure.dynamic.title('获取服务列表')  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        with allure.step(f"发送获取服务列表请求"):
            # 准备请求数据
            json = {"uid": "14174"}
            url = f"{URL}/api/server/get/uid"  # 构建完整的 URL
            headers = {'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvcGVuaWQiOiJvNkttbTVGeTlPd1l5dDRFMEV1RnIwcVFRX1lnIiwidHlwZSI6Ind4bSIsImlkIjoxMzUwLCJyb2xlX2lkIjozLCJpYXQiOjE3NDQxNjcxOTEsImV4cCI6MTc0NDIxMDM5MX0.Dth5i0hqcqI-pQQgcVXaI6WhhRCpV3BUTTncwjXXQPw', 'uid': '14174'}
            response = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            print(f'接口请求响应信息:{response.text}')
            print(f'响应状态码:{response.status_code}')
            print(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            print(f"响应消息：{msg}")
            # 断言响应消息
            assert result.get('msg') == '获取成功', (
                f"响应消息与预期不符\n"
                f"预期消息：{'获取成功'}\n"
                f"实际消息：{result.get('msg')}"
            )
            assert result.get('code') == 1, '响应状态码与预期不符'
            assert apiKey.get_text(response.text, 'data[0].server_name') != '', '未找到对应服务'
            # 数据库断言
            assert apiKey.db_mysql_select(table='dl_server', field='server_name', value=apiKey.get_text(response.text, 'data[0].id')) != '', '未找到对应服务'
        return response

    """发起服务  /api/help/add"""
    def test_addhelp(self, token_fix):
        allure.dynamic.title('发起服务')  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        with allure.step('获取服务列表'):
            res1 = self.test_serverList(token_fix)
        with allure.step('发送发起服务请求'):
            url = f"{URL}/api/help/add"  # 构建完整的 URL
            json = {
                    "openid": "o6Kmm5Fy9OwYyt4E0EuFr0qQQ_Yg",
                    "mu": "尚-1号楼-1108",
                    "wx_id": "1350",
                    "form_id": "the formId is no longer available in develop or trial version of this mini program",
                    "title": f"{apiKey.get_text(res1.text, 'data[0].server_name')}",
                    "des": "day4.9",
                    "total_fee": "2"
            }
            headers = {'token': token, 'uid': uid}
            response = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"发不服务接口返回信息校验接打印"):
            print(f'发起服务接口请求响应信息:{response.text}')
            print(f'响应状态码:{response.status_code}')
            print(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            print(f"响应消息：{msg}")
            # 断言响应消息
            assert result.get('msg') == '操作成功', (
                f"响应消息与预期不符\n"
                f"预期消息：{'操作成功'}\n"
                f"实际消息：{result.get('msg')}"
            )
            assert result.get('code') == 1, '响应状态码与预期不符'
            assert apiKey.get_text(response.text, 'oid') != '', '未找到对应服务'
            # 数据库断言
            assert apiKey.db_mysql_select(table='helplist', field='id', value=apiKey.get_text(response.text, 'oid')) != '', '未找到对应服务'
        return response

    """查看发出的服务  /api/role/del"""
    def test_helpList(self, token_fix):
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        allure.dynamic.title('查看发出的服务')  # 动态获取参数生成标题
        with allure.step('调用新发布服务的接口'):
            res1 = self.test_addhelp(token_fix)
        with allure.step(f"查看发出的服务"):
            # 准备请求数据
            json = {
                "fields": "helplist.*,wxuser.phone,wxuser.dphone,wxuser.avatar_url,wxuser.nick_name",
                "wheres": f"helplist.id={apiKey.get_text(res1.text, 'oid')}",
                "sorts": "helplist.create_time asc"
            }
            url = f"{URL}/api/help/get2"  # 构建完整的 URL
            headers = {'token': token, 'uid': uid}
            res2 = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            print(f'查看发出的服务接口请求响应信息:{res2.text}')
            print(f'响应状态码:{res2.status_code}')
            print(f'响应头:{res2.headers}')
            result = res2.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            print(f"响应消息：{msg}")
            # 断言响应消息
            assert result.get('msg') == '获取成功', (
                f"响应消息与预期不符\n"
                f"预期消息：{'获取成功'}\n"
                f"实际消息：{result.get('msg')}"
            )
            assert result.get('code') == 1, '响应状态码与预期不符'  # 断言响应状态码
            assert apiKey.get_text(res1.text, 'oid') == apiKey.get_text(res2.text, 'data.list[0].id'), '未找到对应服务'   # 断言响应消息
            assert apiKey.db_mysql_select(table='helplist', field='id', value=apiKey.get_text(res2.text, 'data.list[0].id')) != '', '未找到对应服务'  # 数据库断言
            print('查看发出的服务测试通过')
        return res2

